#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 初始化数据库连接
    if (!initDatabase()) {
        qDebug() << "Database initialization failed";
    }
    else
        qDebug() << "Database initialization successed";
}

MainWindow::~MainWindow()
{
    delete ui;
    // 关闭数据库连接
    if (db.isOpen()) {
        db.close();
    }
}

// 增删改查相关操作
void MainWindow::insertData(const QString &device, const QString &version) {
    QSqlQuery query(db);
    query.prepare("INSERT INTO mysql_test (device, version) VALUES (:device, :version)");
    query.bindValue(":device", device);
    query.bindValue(":version", version);

    if (!query.exec()) {
        qDebug() << "插入数据失败:" << query.lastError().text();
    } else {
        qDebug() << "插入数据成功";
    }
}

void MainWindow::queryData() {
    QSqlQuery query("SELECT * FROM mysql_test", db); // 使用已有的数据库连接
    if (!query.isActive()) {
        qDebug() << "查询数据失败:" << query.lastError().text();
        return;
    }

    while (query.next()) {
        QString device = query.value("device").toString();
        QString version = query.value("version").toString();
        qDebug() << "Device:" << device << ", Version:" << version;
    }
}

void MainWindow::updateData(const QString &device, const QString &newVersion) {
    QSqlQuery query(db);
    query.prepare("UPDATE mysql_test SET version = :version WHERE device = :device");
    query.bindValue(":version", newVersion);
    query.bindValue(":device", device);

    if (!query.exec()) {
        qDebug() << "更新数据失败:" << query.lastError().text();
    } else {
        qDebug() << "更新数据成功";
    }
}

void MainWindow::queryUpdatedData(const QString &device) {
    QSqlQuery query(db);
    query.prepare("SELECT * FROM mysql_test WHERE device = :device");
    query.bindValue(":device", device);

    if (!query.exec()) {
        qDebug() << "查询更新后数据失败:" << query.lastError().text();
        return;
    }

    while (query.next()) {
        QString deviceName = query.value("device").toString();
        QString version = query.value("version").toString();
        qDebug() << "更新后 - Device:" << deviceName << ", Version:" << version;
    }
}

// 初始化数据库连接
bool MainWindow::initDatabase() {
    db = QSqlDatabase::addDatabase("QMYSQL"); // 使用 MySQL 驱动
    db.setHostName("firmware.vkinging.com");
    db.setPort(1984);
    db.setDatabaseName("VKINGING");
    db.setUserName("yjtest");
    db.setPassword("vkyj2024");

    if (!db.open()) {
        qDebug() << "数据库连接失败:" << db.lastError().text();
        return false;
    } else {
        qDebug() << "数据库连接成功";
        return true;
    }
}
